package fr.obsmip.sedoo.core.dao;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.opengis.metadata.Metadata;

import fr.sedoo.commons.client.util.StringUtil;
import fr.sedoo.commons.domain.User;
import fr.sedoo.commons.metadata.utils.dao.MetadataDAO;
import fr.sedoo.commons.metadata.utils.domain.MetadataTools;
import fr.sedoo.commons.metadata.utils.domain.SedooMetadata;
import fr.sedoo.commons.metadata.utils.domain.Summary;
import fr.sedoo.metadata.client.util.Iso19115DateUtil;
import fr.sedoo.rbv.geonetwork.domain.GeonetworkUser;
import fr.sedoo.rbv.geonetwork.request.MetadataAddOrUpdateWithIdRequest;
import fr.sedoo.rbv.geonetwork.request.MetadataByIdRequest;
import fr.sedoo.rbv.geonetwork.request.MetadataDeleteRequest;
import fr.sedoo.rbv.geonetwork.request.MySummaryRequest;

public class GeonetworkMetadataDAO implements MetadataDAO {

	@Override
	public Metadata getMetadataById(String id, User user) throws Exception {
		
		MetadataByIdRequest request = null;
		if (user != null)
		{
			request = new MetadataByIdRequest(id, (GeonetworkUser) user);
		}
		else
		{
			request = new MetadataByIdRequest(id);
		}
		
		boolean result = request.execute();
		if (result == true)
		{
			return request.getMetadata();
		}
		else
		{
			throw new Exception();
		}
	}
	
	public List<Summary> getSummaries(User user) throws Exception  
	{
		MySummaryRequest request = new MySummaryRequest((GeonetworkUser) user);
		boolean result = request.execute();
		if (result == true)
		{
			return request.getSummaries();
		}
		else
		{
			throw new Exception();
		}
	}

	@Override
	public String getPDFURL(String metadataId, User user) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean deleteMetadataByUuid(String uuid, User user) throws Exception {
		MetadataDeleteRequest request = null;
		if (user == null)
		{
			request = new MetadataDeleteRequest(uuid);
		}
		else
		{
			request = new MetadataDeleteRequest(uuid, (GeonetworkUser) user);
		}
		return request.execute();
	}

	@Override
	public SedooMetadata saveMetadata(SedooMetadata metadata, User user) throws Exception 
	{
		SedooMetadata aux = (SedooMetadata) metadata;
		String uuid = aux.getUuid();
		if (StringUtil.isEmpty(uuid))
		{
			uuid = UUID.randomUUID().toString();
			aux.setUuid(uuid);
		}
		
		//MAJ date
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		metadata.setMetadataDate(simpleDateFormat.format(new Date()));
		
		String content = MetadataTools.toISO19139(aux);
		MetadataAddOrUpdateWithIdRequest request = null;
		
		if (user == null)
		{
			request = new MetadataAddOrUpdateWithIdRequest(content);
		}
		else
		{
			request = new MetadataAddOrUpdateWithIdRequest(content, (GeonetworkUser) user);
		}
		boolean executionResult = request.execute();
		if (executionResult == true)
		{
			return metadata;
		}
		else
		{
			throw new Exception();
		}
	}


}
